<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-03 11:15:37
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;

use App\Http\Services\Service;
use App\Models\Company;
use App\Models\MpcSummaryStorage;
use App\Models\ProColor;
use App\Repositories\MarketOfferPromotionsRepository;
use App\Repositories\MarketOfferPromotionsRolsRepository;
use App\Repositories\MarketOfferRepository;
use App\Repositories\MarketOrderDetailsRepository;
use App\Repositories\MarketRetailDetailsRepository;

/**
 * @property MarketOfferRepository $repository
 * @property MarketOfferPromotionsRepository $promotion
 * @property MarketOfferPromotionsRolsRepository $role 
 * @property MarketOrderDetailsRepository $order 
 * @property MarketRetailDetailsRepository $retail  
 */
class OfferService extends Service
    {
    public $details;

    public function boot(
        MarketOfferRepository $repository,
        MarketOfferPromotionsRepository $promotion,
        MarketOfferPromotionsRolsRepository $role,
        MarketOrderDetailsRepository $order,
        MarketRetailDetailsRepository $retail,
    ) {
        $this->repository = $repository;
        $this->promotion  = $promotion;
        $this->role       = $role;
        $this->order      = $order;
        $this->retail     = $retail;
        }
    protected function enable()
        {
        $data = $this->promotion->whereIn("id", $this->getRequestIds())->first();
        if ($data->status_id == 0)
            fail("单据【{$data->code}】已启用！");
        return enable($data);
        }
    public function mateOffer()
        {
        $request       = request();
        $material_id   = $request->material_id; //
        $type_id       = $request->type_id; //
        $department_id = $request->department_id;
        $service_id    = $request->service_id;
        $quantity      = $request->quantity;
        $grad          = $request->grad;
        $color         = ProColor::whereId($request->color_id)->first();
        $customer      = Company::whereId($request->customer_id)->first();
        //匹配基础报价
        $offer = $this->repository->mate($material_id, $type_id, $department_id);
        //匹配优惠卷
        $promotion = $this->promotion->mate($service_id, $grad, $material_id, $color, $customer, $quantity, $department_id);
        return ['offer' => $offer, 'promotion' => $promotion];
        }
    protected function disable()
        {
        $data = $this->promotion->whereIn("id", $this->getRequestIds())->first();
        if ($data->status_id == -1)
            fail("单据【{$data->code}】未启用！");
        return enable($data, false);
        }
    public function role()
        {
        $data = $this->role->condition(request())->getGrid();
        return $data;
        }
    public function promotion()
        {
        $data = $this->promotion->condition(request())->getGrid();
        return $data;
        }
    public function list()
        {
        $data = $this->repository->condition(request())->whereIshistory(0)->getGrid();
        return $data;
        }
    public function history()
        {
        $data = $this->repository->condition(request())->whereIshistory(1)->getGrid();
        return $data;
        }

    public function materiallist()
        {
        $department_offer = $this->repository->where("department_id", "=", auth()->user()->department_id)->whereStatus_id(1)->get();

        $data = $this->repository->condition(request())->where(function ($query) use ($department_offer)
            {
            //通用报价中，去除部门报价重复部分
            $query->orWhere(function ($q) use ($department_offer)
                {
                $q->where("department_id", "=", "0");
                if ($department_offer) {
                    $department_offer->filter(function ($dep_offer) use ($q)
                        {
                        $q->where("material_id", "<>", $dep_offer->material_id);
                        $q->where("type_id", "<>", $dep_offer->type_id);
                        });
                    }
                });
            $query->orWhere("department_id", "=", auth()->user()->department_id);
            })
            ->whereStatus_id(1)
            ->getGrid();
        return $data;
        }
    protected function save()
        {
        $data  = request()->toArray();
        $id    = isset($data['id']) && !isEmpty($data['id']) && is_numeric($data['id']) ? $data['id'] : 0;
        $gdata = null;
        if ($id !== 0) {
            $gdata = $this->repository->whereId($id)->getOne();
            if ($gdata->status_id != '0') {
                fail("报价状态[{$gdata->status->name}],禁止编辑");
                }
            }
        if (isEmpty($data['department_id'] ?? '')) {
            $data['department_id'] = 0;
            }
        //查找老的报价单
        $olddata = $this->repository
            ->whereMaterial_id($data['material_id'])
            ->whereType_id($data['type_id'])
            ->whereDepartment_id($data['department_id'])
            ->whereIshistory(0)
            ->first();

        if ($olddata && ($olddata['sale_price'] != $data['sale_price'] || $olddata['pro_price'] != $data['pro_price'])) {
            unset($data['id'], $data['code']);
            $data['old_id']     = $olddata->old_id == 0 ? $olddata['id'] : $olddata->old_id;
            $olddata->ishistory = 1;
            $olddata->save();
            }
        $data = $this->repository->autosave($data);
        if ($data->old_id == 0) {
            $data->old_id = $data->id;
            $data->save();
            }
        return $data;
        }

    protected function savepromotion()
        {
        $data = request()->toArray();
        $id   = is_numeric($data['id'] ?? "") ? $data['id'] : 0;
        if ($id !== 0) {
            $gdata = $this->promotion->whereId($id)->getOne();
            if ($gdata->status_id == 0) {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            $this->validPromotion($gdata);
            }
        return $this->promotion->autosave($data, false, ['roles']);
        }
    /**
     * 验证报价优惠是否被使用
     * @param mixed $data
     * @return void
     * @author sunkaiyuan
     */
    private function validPromotion($data)
        {
        $order_data = $this->order->wherePromotion_code($data['code'])->first();
        if ($order_data) {
            fail("已被报色单【{$order_data['code']}】使用，禁止编辑");
            }
        $order_data = $this->retail->wherePromotion_code($data['code'])->first();
        if ($order_data) {
            fail("已被发货单【{$order_data['code']}】使用，禁止编辑");
            }
        }
    protected function audit()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($Order)
            {

            auditSave($Order);
            });
        }
    /**
     * Summary of noaudit
     * @return mixed
     */
    protected function noaudit()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($Order)
            {
            auditSave($Order, false);
            });
        }

    protected function delete()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id == 1)
                fail("单据已审核！");
            $v->delete();
            });
        }

    public function printReport()
        {
        $data = $this->repository->relation()->whereIn("id", $this->getRequestIds())->get();
        return createReport($data->toArray());
        }
    }